package com.css.fxfzdzzh.modules.mapManagement.service;

import cn.hutool.core.util.IdUtil;
import com.css.fxfzdzzh.base.attachment.entity.Attachment;
import com.css.fxfzdzzh.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzdzzh.base.attachment.repository.AttachmentInfoRepository;
import com.css.fxfzdzzh.base.attachment.service.AttachmentInfoService;
import com.css.fxfzdzzh.base.dict.repository.DictItemRepository;
import com.css.fxfzdzzh.base.dict.repository.DictRepository;
import com.css.fxfzdzzh.base.dict.repository.entity.DictEntity;
import com.css.fxfzdzzh.base.dict.repository.entity.DictItemEntity;
import com.css.fxfzdzzh.common.utils.BeanUtil;
import com.css.fxfzdzzh.common.utils.ZipDownloadUtil;
import com.css.fxfzdzzh.constants.YNEnum;
import com.css.fxfzdzzh.modules.mapManagement.param.MapQueryParam;
import com.css.fxfzdzzh.modules.mapManagement.repository.MapRepository;
import com.css.fxfzdzzh.modules.mapManagement.vo.MapVO;
import com.css.fxfzdzzh.modules.mapManagement.vo.MapViewVO;
import com.css.fxfzdzzh.modules.surfaceRupture.repository.SurfaceRuptureRepository;
import com.css.fxfzdzzh.modules.surfaceRupture.vo.SurfaceRuptureNumVO;
import com.css.fxfzdzzh.modules.taskManage.entity.TaskEntity;
import com.css.fxfzdzzh.modules.taskManage.repository.TaskRepository;
import com.css.fxfzdzzh.modules.taskManage.vo.TaskNumVO;
import com.css.fxfzdzzh.util.CreateGson;
import com.css.fxfzdzzh.util.PlatformObjectUtils;
import com.css.fxfzdzzh.util.RemoteTransfer;
import com.css.fxfzdzzh.util.UUIDGenerator;
import com.css.fxfzdzzh.web.PlatformSessionContext;
import com.css.fxfzdzzh.zcpt.sys.entity.SUser;
import com.css.fxfzdzzh.zcpt.sys.service.SUserService;
import org.slw.common.helper.PropsHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;

import com.css.fxfzdzzh.modules.mapManagement.entity.Map;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Dbj
 * @date 2023年05月16日  10:23
 */
@Service
public class MapService {

    @Resource
    MapRepository mapRepository;
    @Resource
    SUserService sUserService;
    @Resource
    private AttachmentInfoRepository attachmentInfoRepository;
    @Value("${file.localDir}")
    private String localDir;
    @Resource
    private DictRepository dictRepository;
    @Resource
    private DictItemRepository dictItemRepository;
    @Resource
    TaskRepository taskRepository;
    @Resource
    SurfaceRuptureRepository surfaceRuptureRepository;
    @Resource
    private AttachmentInfoService attachmentInfoService;

    public void uploadMap(MapVO mapVO) throws Exception {
        @NotBlank(message = "图件分类不能为空") String mapLevel1Category = mapVO.getMapLevel1Category();
        if("7".equals(mapLevel1Category)){
            //地质灾害危险性评估-评估结果
            String mapLevel2Category = mapVO.getMapLevel2Category();
            if("11".equals(mapLevel2Category) || "12".equals(mapLevel2Category) || "13".equals(mapLevel2Category)){
                //11XX度地震滑坡风险分布图
                //12黄土高原50年超越概率XX%地震滑坡危险等级评价图
                //13地震滑坡危险性概率分布图
                //删除之前生成的这三种之中的任意一种 这就是说只能存在一种图
                List<String> strings = Arrays.asList("13", "12", "11");
                mapRepository.deleteSameBatch(mapVO.getNum(),strings,mapVO.getMapLevel1Category(),mapLevel2Category);
            }else if("14".equals(mapLevel2Category) || "15".equals(mapLevel2Category) || "16".equals(mapLevel2Category)|| "17".equals(mapLevel2Category)){
                //14砂土液化分区图
                //15砂土液化等级分区图
                //16砂土液化危险等级评价图
                //17软土震陷分区图
                //删除之前生成的这四种之中的任意一种 这就是说只能存在一种图
                List<String> strings = Arrays.asList("14", "15", "16","17");
                mapRepository.deleteSameBatch(mapVO.getNum(),strings,mapVO.getMapLevel1Category(),mapLevel2Category);
            }
        }
        Map map = new Map();
        map.setDmId(UUIDGenerator.getUUID());
        BeanUtils.copyProperties(mapVO,map);
        map.setUploadTime(new Date());
        String userId = PlatformSessionContext.getUserID();
        map.setUploadUserId(userId);
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        map.setUploadUserName(sUser.getUserName());
        String district = mapVO.getProvince();
        if(PlatformObjectUtils.isNotEmpty(mapVO.getCity())){
            district+=mapVO.getCity();
        }
        if(PlatformObjectUtils.isNotEmpty(mapVO.getArea())){
            district+=mapVO.getArea();
        }
        map.setDistrict(district);
        map.setDelFlag(YNEnum.N.toString());
        map.setProvince(mapVO.getProvince());
        map.setCity(mapVO.getCity());
        map.setArea(mapVO.getArea());
        mapRepository.saveMap(map);
        transReportMsgToCpxx(map,mapVO.getUnit());
    }

    private void transReportMsgToCpxx(Map map, String unit) throws Exception {
        if (PlatformObjectUtils.isNotEmpty(map.getNum())) {
            AttachmentInfoEntity attach = attachmentInfoService.getAttach(map.getAttachmentId());
            String fileDirId = attach.getFileDirId();
            String attachPath = attach.getAttachPath();

            String userId = PlatformSessionContext.getUserID();
            String userJson = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
            //获取创建人单位
            String orgName = sUser.getOrgName();
            Properties configGroup = PropsHelper.loadProps("slw-config.properties");
            String url = configGroup.getProperty("cpxxRestUrl") + "/theMap/dockingOtherSystem";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            headers.set("Authorization", IdUtil.simpleUUID());
            File newfile = new File(fileDirId+File.separator+attachPath);
            java.util.Map<String, String> valueMap = new HashMap<>();
            valueMap.put("meansName", map.getMapName());
            valueMap.put("flag", "7");
            valueMap.put("province", map.getProvince());
            valueMap.put("city", map.getCity());
            valueMap.put("county", map.getArea());
            valueMap.put("createUser", userId);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            valueMap.put("plotTime",dateFormat.format(new Date()));
            valueMap.put("draftingUnit", unit);
            valueMap.put("publishingUnit", orgName);
            valueMap.put("pictureDescribe", map.getMapDesc());
            TaskEntity task = taskRepository.viewTask(map.getNum());
            String mapLevel2Category = map.getMapLevel2Category();
            String disasterType = "";
            if ("11".equals(mapLevel2Category) || "12".equals(mapLevel2Category) || "13".equals(mapLevel2Category)) {
                disasterType="地震滑坡";
            } else if ("14".equals(mapLevel2Category) || "15".equals(mapLevel2Category) || "16".equals(mapLevel2Category) || "17".equals(mapLevel2Category)) {
                disasterType="砂土液化";
            } else if ("16".equals(mapLevel2Category)) {
                disasterType="软土震陷";
            }
            valueMap.put("disasterType",disasterType);
            valueMap.put("keyword", task.getTaskName() + ","+disasterType);
            java.util.Map<String, MultipartFile> fileParams = new HashMap<>();
            //本地文件转为MultipartFile
            MultipartFile file = RemoteTransfer.pathToMultipartFile(newfile);
            fileParams.put("file", file);
            String res = RemoteTransfer.uploadFile(url, fileParams, valueMap, null);

        }
    }

    public java.util.Map<String, Object> mapPage(MapQueryParam param, int curPage, int pageSize) {
        java.util.Map<String, Object> map = mapRepository.mapPage(param, curPage, pageSize);
        List<Map> list = (List<Map>) map.get("rows");
        if(PlatformObjectUtils.isNotEmpty(list) && list.size()>0){
            List<DictEntity> all = dictRepository.findAll();
            java.util.Map<String, String> dictMap = all.stream().collect(Collectors.toMap(DictEntity::getDictId, DictEntity::getDictName));
            list.forEach(entity->{
                DictItemEntity dictItemEntity = dictItemRepository.findOneByDictItemIdAndDictId(entity.getMapLevel1Category(),entity.getMapLevel2Category());
                entity.setMapLevel2Category(dictItemEntity.getDictItemName());
                entity.setMapLevel1Category(dictMap.get(entity.getMapLevel1Category()));
            });
        }
        return map;
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(List<String> dmIdList) throws Exception{
        int count = mapRepository.delete(dmIdList);
        if(count==0){
            throw new RuntimeException("删除失败");
        }
    }

    public void download(List<String> attacheIdList, HttpServletResponse resp) {
        List<File> fileList = new ArrayList<>();
        attacheIdList.forEach(attacheId->{
            AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(attacheId);
            File file = new File(attach.getFileDirId()+File.separator+attach.getAttachPath());
            fileList.add(file);
        });
        if(fileList.size()>0){
            ZipDownloadUtil.zipDownload(resp,localDir,"图件"+System.currentTimeMillis()+".zip",fileList);
        }
    }

    public List<TaskNumVO> getTaskList() {
        String userId = "a23236fda79244618aa93da19bd22ff2";
        List<TaskEntity> taskEntities = taskRepository.getAllTask(userId);
        List<TaskNumVO> vos = new ArrayList<>();
        if(PlatformObjectUtils.isNotEmpty(taskEntities)){
            taskEntities.forEach(task->{
                TaskNumVO numVO = new TaskNumVO();
                numVO.setNum(task.getTaskNum());
                numVO.setName(task.getTaskName());
                vos.add(numVO);
            });
        }
        return vos;
    }

    public List<SurfaceRuptureNumVO> getRuptureList() {
        return surfaceRuptureRepository.getRuptureList();
    }

    public MapViewVO getById(String dmId) {
        Map map = mapRepository.getById(dmId);
        if(map==null){
            return new MapViewVO();
        }
        MapViewVO vo = new MapViewVO();
        AttachmentInfoEntity attach = attachmentInfoRepository.getAttach(map.getAttachmentId());
        BeanUtil.copyPropertiesIgnoreEmpty(map,vo);
        vo.setAttachList(Arrays.asList(attach));
        return vo;
    }
}
